package com.hzy.ums.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.hzy.constant.Constants;
import com.hzy.ums.domain.MemberLogininfor;
import com.hzy.ums.mapper.MemberLogininforMapper;
import com.hzy.utils.IpUtils;
import com.hzy.wechat.WechatPayData;
import com.hzy.wechat.feign.WxAppletFeign;
import com.hzy.wechat.response.WechatUserAuth;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.EncryptUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.hzy.ums.domain.bo.MemberBo;
import com.hzy.ums.domain.vo.MemberVo;
import com.hzy.ums.domain.Member;
import com.hzy.ums.mapper.MemberMapper;
import com.hzy.ums.service.IMemberService;
import org.springframework.util.Base64Utils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 会员信息Service业务层处理
 *
 * @author zengxin
 * @date 2023-10-19
 */
@RequiredArgsConstructor
@Service
public class MemberServiceImpl implements IMemberService {

    private final MemberMapper baseMapper;
    @Value("${aes.key}")
    private String aesKey;

    private final MemberLogininforMapper memberLogininforMapper;

    private final WxAppletFeign wxAppletFeign;


    /**
     * 查询会员信息
     */
    @Override
    public MemberVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询会员信息列表
     */
    @Override
    public TableDataInfo<MemberVo> queryPageList(MemberBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Member> lqw = buildQueryWrapper(bo);
        Page<MemberVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询会员信息列表
     */
    @Override
    public List<MemberVo> queryList(MemberBo bo) {
        LambdaQueryWrapper<Member> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Member> buildQueryWrapper(MemberBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Member> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), Member::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), Member::getPassword, bo.getPassword());
//        lqw.eq(StringUtils.isNotBlank(bo.getPhoneHidden()), Member::getPhoneHidden, bo.getPhoneHidden());
        lqw.eq(StringUtils.isNotBlank(bo.getMark()), Member::getMark, bo.getMark());
        lqw.eq(bo.getStatus() != null, Member::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), Member::getAvatar, bo.getAvatar());
        lqw.eq(bo.getGender() != null, Member::getGender, bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), Member::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), Member::getProvince, bo.getProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getCountry()), Member::getCountry, bo.getCountry());
        lqw.eq(bo.getBirthday() != null, Member::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getSpreadUid()), Member::getSpreadUid, bo.getSpreadUid());
        lqw.eq(bo.getSpreadTime() != null, Member::getSpreadTime, bo.getSpreadTime());
//        lqw.eq(StringUtils.isNotBlank(bo.getLevel()), Member::getLevel, bo.getLevel());
//        lqw.eq(bo.getIntegral() != null, Member::getIntegral, bo.getIntegral());
        return lqw;
    }

    /**
     * 新增会员信息
     */
    @Override
    public Boolean insertByBo(MemberBo bo) {
        Member add = BeanUtil.toBean(bo, Member.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会员信息
     */
    @Override
    public Boolean updateByBo(MemberBo bo) {
        Member update = BeanUtil.toBean(bo, Member.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Member entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除会员信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void validate(String phone) {
        LambdaQueryWrapper<Member> qw = new LambdaQueryWrapper<Member>();
        qw.eq(Member::getPhoneEncrypted, EncryptUtils.encryptByRsa(phone, aesKey));
        Member member = baseMapper.selectOne(qw);
        if (member != null){
            throw new RuntimeException("该手机号已被占用");
        }
    }

    /**
     * 校验验证码有效性
     * @param uuid 唯一标识
     * @param inputCode 输入的验证码
     */
    @Override
    public void validateVerifyCode(String uuid, String inputCode){
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = (String) RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        } else if (!inputCode.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }


    @Override
    public void insertLoginRecord(Long memberId) {
        Member member = baseMapper.selectById(memberId);
        Assert.notNull(member, Constants.LOGIN_FAIL);
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        MemberLogininfor memberLogininfor = new MemberLogininfor();
        memberLogininfor.setMemberId(memberId);
        memberLogininfor.setPhone(member.getPhoneHidden());
        memberLogininfor.setOs(userAgent.getOperatingSystem().getName());
        memberLogininfor.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        memberLogininfor.setBrowser(userAgent.getBrowser().getName());
        memberLogininfor.setLoginLocation(AddressUtils.getRealAddressByIP(memberLogininfor.getIpaddr()));
        memberLogininfor.setLoginTime(new Date());
        memberLogininforMapper.insert(memberLogininfor);
    }


    @Override
    public WechatUserAuth getWechatUserAuth(String data) {
        JSONObject jsonObject = JSONObject.parseObject(new String(Base64Utils.decodeFromString(data)));
//        BindOpenIdRequest request = JSON.parseObject(new String(Base64Utils.decodeFromString(data)), BindOpenIdRequest.class);
        String wxOpenId = wxAppletFeign.getWxOpenId(WechatPayData.appId, WechatPayData.secret, jsonObject.getString("code"));
        WechatUserAuth userToken = JSON.parseObject(new String(Base64Utils.decodeFromString(wxOpenId)), WechatUserAuth.class);
        if (userToken == null){
            throw new RuntimeException("授权失败，请重试");
        }
        return userToken;
    }

}
